package dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import beans.Admin;
import beans.Agent;

import utils.HibernateUtil;






public class AdminDao {
	
	

	Transaction tr=null;
	private SessionFactory sessionFactory;
	
	/**
	 * 通过管理员ID返回指定管理员信息
	 * 
	 *            管理员ID
	 * @return
	 */
	public Admin getAdminById(int adminId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Admin admin = (Admin) session.get(Admin.class, adminId);
		tr.commit();
		session.close();
		return admin;
	}
	
	/**
	 * 删除管理员
	 */
	public void delete(Admin admin) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(admin);
		tr.commit();
		session.close();
	}
	
	/**
	 * 修改管理员
	 */
	public void edit(Admin admin) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(admin);
		tr.commit();
		session.close();
	}
	
	public Agent get(String username,String password){
		
		Session session=sessionFactory.openSession();
		Agent admin=null;

		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Agent.class);
		c.add(Restrictions.eq("name",username));
		c.add(Restrictions.eq("password",password));
		List<Agent> result=c.list();
		if(result.iterator().hasNext()){
			admin= (Agent) result.iterator().next();
		}
		
		tr.commit();
		
		session.close();
		return admin;
		
	}
	
	public void save(Admin admin){
		Session session=sessionFactory.openSession();
		
		tr=session.beginTransaction();
		session.save(admin);
		tr.commit();
		session.close();
		
	}
	
	public List<Admin> getAll(){
		Session session=sessionFactory.openSession();
		
		tr=session.beginTransaction();
		Criteria c=session.createCriteria(Admin.class);
		List<Admin> admins=c.list();
		tr.commit();
		
		session.close();
		return admins;
	}
	
	public AdminDao() {
		sessionFactory=HibernateUtil.getSessionFactory();
	}
}
